package com.billard.config;


import com.billard.mapper.UserMapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomUserDetailsService implements UserDetailsService {
//1
    private UserMapper userMapper;

    public CustomUserDetailsService(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1. 查用户
        com.billard.entity.User user = userMapper.selectByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 2. 查角色和权限
        List<String> permissions = userMapper.selectPermissionsByUserId(user.getId());

        // 3. 封装为 Spring Security 用户
        return User
                .withUsername(user.getUsername())
                .password(user.getPassword()) // 数据库里要加密过
                .authorities(permissions.toArray(new String[0])) // 比如 ["user:view", "user:add"]
                .build();
    }
}